# -*- coding: utf-8 -*-
'''eof
name:企业近2年信贷未结清余额年增长率
code:EC11_Past2YearsUpaidBalGroRatio_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import datetime
from dateutil.relativedelta import relativedelta 
from dateutil.parser import parse

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
    获取表信息
    :param data:表上层的字典对象
    :param tableName:表的名字
    :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
    :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
    :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]
    
def isfloat(x):
    '''
    判断x为float类型且x大于等于0
    '''
    try:
        if isinstance(float(x),float) and float(x) >= 0:
            if str(x) in ['inf','infinity','INF','INFINITY','True','NAN','nan',\
                  'False','-inf','-INF','-INFINITY','-infinity','NaN','Nan',]:
                return False
            else:
                return float(x)
        else:
            return False
    except:
        return False


def EC11_Past2YearsUpaidBalGroRatio_2D():
    data = EC_DSJ_2D.get('data')
    # 借贷账户信息
    EDA = getTable(data, 'EDA', 1, 0)
    EDB = getTable(data, 'EDB', 1, 0)
    if EDA == [{}] and EDB == [{}]:
        return u'缺失值'
    elif EDA == 0 and EDB == 0:
        return 0
    else:
        ED01 = getTable(EDA[0], 'ED01', 0, 1)
        ED04 = getTable(EDB[0], 'ED04', 0, 1)
        if ED01 == [{}] and ED04 == [{}]:
            return u'缺失值'
        elif ED01 == 0 and ED04 == 0:
            return 0
        else:
            factor1 = []
            factor2 = []
            factor3 = []
            factor4 = []
            ED01_cont = 0
            ED04_cont = 0
            nowTime = datetime.datetime.now().date()
            oneYearStratTime = nowTime - relativedelta(days = 360)
            twoYearStratTime = nowTime - relativedelta(days = 720)
            for i in ED01:
                try:
                    # 基本信息段
                    ED01A = getTable(i, 'ED01A', 1, 1)
                    ED01B = getTable(i, 'ED01B', 1, 1)
                    if ED01A == [{}] or ED01B == [{}]:
                        ED01_cont += 1
                        factor1.append(None)
                    elif ED01A == 0 or ED01B == 0:
                        factor1.append(0)      #0加在哪个上都可以
                    else:
                        # 账户状态
                        ED01AD01 = ED01A[0].get("ED01AD01")
                        #账户开立时间
                        ED01AR01 = parse(ED01A[0].get("ED01AR01")).date()
                        #账户余额
                        ED01BJ01 = float(ED01B[0].get("ED01BH")[0].get("ED01BJ01"))
                        if ED01AD01 not in null_type_list and ED01AR01 not in null_type_list and ED01BJ01 not in null_type_list \
                        and isfloat(ED01BJ01):
                            if ED01AD01 in [1,"1"] and oneYearStratTime <= ED01AR01 < nowTime:
                                factor1.append(ED01BJ01)
                            elif ED01AD01 in [1,"1"] and twoYearStratTime <= ED01AR01 < oneYearStratTime:
                                factor3.append(ED01BJ01)
                            else:
                                pass
                        else:
                            ED01_cont +=1
                except:
                    ED01_cont += 1
            for i in ED04:
                try:
                    # 基本信息段
                    ED04A = getTable(i, 'ED04A', 1, 1)
                    # 账户状态
                    ED04B = getTable(i, 'ED04B', 1, 1)
                    if ED04A == [{}] or ED04B == [{}]:
                        ED04_cont += 1
                        factor1.append(None)
                    elif ED04A == 0 or ED04B == 0:
                        factor2.append(0)      #0加在哪个上都可以
                    else:
                        # 账户状态
                        ED04BD01 = ED04B[0].get("ED04BD01")
                        #账户开立时间
                        ED04AR01 = parse(ED04A[0].get("ED04AR01")).date()
                        #账户余额
                        ED04BJ01 = float(ED04B[0].get("ED04BJ01"))
                        if ED04BD01 not in null_type_list and ED04AR01 not in null_type_list and ED04BJ01 not in null_type_list \
                        and isfloat(ED04BJ01):
                            if ED04BD01 in [1,"1"] and oneYearStratTime <= ED04AR01 < nowTime:
                                factor2.append(ED04BJ01)
                            elif ED04BD01 in [1,"1"] and twoYearStratTime <= ED04AR01 < oneYearStratTime:
                                factor4.append(ED04BJ01)
                            else:
                                pass
                        else:
                            ED04_cont +=1
                            
                except:
                    ED04_cont +=1
        if ED01_cont + ED04_cont == len(ED01) + len(ED04):
            return u'缺失值'
        factor1 = filter(lambda x:x is not None, factor1)
        factor2 = filter(lambda x:x is not None, factor2)
        factor3 = filter(lambda x:x is not None, factor3)
        factor4 = filter(lambda x:x is not None, factor4)
        
        if sum(factor3) + sum(factor4) == 0:
            return u'缺失值'
        else:
            return (sum(factor1)+sum(factor2))/(sum(factor3)+sum(factor4)) - 1

result = EC11_Past2YearsUpaidBalGroRatio_2D()
